package com.cyx.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cyx.common.core.domain.R;
import com.cyx.common.core.enums.ResultCode;
import com.cyx.system.domain.SysUser;
import com.cyx.system.mapper.SysUserMapper;
import com.cyx.system.service.ISysUserService;
import com.cyx.system.utils.BCryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public R<Void> login(String userAccount, String password) {
        // 通过账号去数据库中查询对应的用户信息
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper
                .select(SysUser::getPassword).eq(SysUser::getUserAccount, userAccount));

        // 用户不存在
        if(sysUser == null) {
            return R.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        // 密码匹配成功
        if(BCryptUtils.matches(password, sysUser.getPassword())) {
            return R.ok();
        }

        // 账号或密码错误
        return R.fail(ResultCode.FAILED_LOGIN);
    }
}
